package com.hp.bon.sgw.threads;

import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;

import org.quartz.CronExpression;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import com.hp.bon.sgw.bean.CapabilityLifeBean;
import com.hp.bon.sgw.domain.SgwViewDao;
import com.hp.bon.sgw.service.ConfigService;

/**
 * @desc   每分钟检查能力生命周期状态，并进行状态更新
 * @author wanghan
 *
 */
public class CapabilityLifeStatusThread {
	final public static org.slf4j.Logger logger = LoggerFactory.getLogger(CapabilityLifeStatusThread.class);
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private SgwViewDao sgwViewDao;

	@Scheduled(cron="0 * * * * ?")
	public void work() {
		logger.info("CapabilityLifeStatusService work");
		try {
			refreshLifeStatus();
		} catch (Exception e) {
			logger.warn("CapabilityLifeStatusService work error", e);
		}
	}
	
	private void refreshLifeStatus() throws Exception{
		ConcurrentHashMap<String,Boolean> capStatusMapNew = this.getCurStatus();
		CapabilityLifeManager.getInstance().refresh(capStatusMapNew);
	}
	
	private ConcurrentHashMap<String,Boolean> getCurStatus() throws Exception{
		ConcurrentHashMap<String,Boolean> capStatusMap = new ConcurrentHashMap<String,Boolean>();
		
		ConcurrentHashMap<String, CapabilityLifeBean> capLifeCfgMap = configService.getCapabilityLifeCfgMap();
		Date now = new Date();
		TimeZone timeZone = TimeZone.getDefault();
		for (String hostServiceContextId : capLifeCfgMap.keySet()) {
			CapabilityLifeBean lifeBean = capLifeCfgMap.get(hostServiceContextId);
			if(!CronExpression.isValidExpression(lifeBean.getLifeRule())){
				logger.error(String.format("Expression is not valid: hostId=%s, serviceContextId=%s, ex='%s'", 
						lifeBean.getHostId(), lifeBean.getServiceContextId(), lifeBean.getLifeRule()));
				continue;
			}
			CronExpression cronEx = new CronExpression(lifeBean.getLifeRule());
			cronEx.setTimeZone(timeZone);
			boolean status = cronEx.isSatisfiedBy(now);
			if("0".equals(lifeBean.getLifeFlag())){
				if(status){
					capStatusMap.put(hostServiceContextId, false);
				}else{
					capStatusMap.put(hostServiceContextId, true);
				}
			}else{
				capStatusMap.put(hostServiceContextId, status);
			}
			
		}
		return capStatusMap;
	}
}

